﻿package ui {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	import flash.ui.Keyboard;
	public class TextBox extends UIItem {
		private static const LABEL_WIDTH:Number = NaN;
		
		private var label:String;
		private var defaultText:String;
		public var w:Number = 50;
		public var labelWidth:Number = NaN;
		public var labelColor:int = 0x000000;
		
		protected var content:Sprite = new Sprite();
		protected var labelTxt:TextField = new TextField();
		protected var txt:TextField = new TextField();
		
		public function TextBox(label:String, defaultText:String = "", options:Object = null) {
			this.label = label;
			this.defaultText = defaultText;
			applyOptions(options);
			
			addChild(content);
			
			labelTxt.defaultTextFormat = new TextFormat("Tahoma", 9, labelColor);
			labelTxt.text = label;
			labelTxt.selectable = labelTxt.tabEnabled = labelTxt.mouseEnabled = false;
			content.addChild(labelTxt);
			
			txt.defaultTextFormat = new TextFormat("Tahoma", 9, null, true, null, null, null, null, TextFormatAlign.LEFT);
			txt.text = defaultText;
			txt.width = w;
			txt.height = 15;
			txt.type = TextFieldType.INPUT;
			txt.border = true;
			txt.borderColor = 0xDBDBDB;
			txt.background = true;
			txt.backgroundColor = 0xEFEFEF;
			txt.addEventListener(FocusEvent.FOCUS_OUT, focusOut);
			txt.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
			txt.tabIndex = nextTabIndex++;
			content.addChild(txt);
			
			resizeLabel(labelWidth);
			
		}
		public function resizeLabel(w:Number):void {
			labelWidth = w;
			if (isNaN(labelWidth)) {
				labelTxt.autoSize = TextFieldAutoSize.LEFT;
				labelWidth = labelTxt.width;
			} else {
				labelTxt.autoSize = TextFieldAutoSize.LEFT;
				var lh:Number = labelTxt.height;
				labelTxt.autoSize = TextFieldAutoSize.NONE;
				labelTxt.width = labelWidth;
				labelTxt.height = lh;
			}
			txt.x = labelTxt.width+3;
		}
		
		public function get text():String {
			return txt.text;
		}
		public function set text(v:String):void {
			txt.text = v;
		}	
		public function get backgroundColor():uint {
			return txt.backgroundColor;
		}
		public function set backgroundColor(v:uint):void {
			txt.backgroundColor = v;
		}
		private function keyDown(e:KeyboardEvent):void {
			if (e.keyCode == Keyboard.ENTER) updateChange();
		}
		private function focusOut(e:FocusEvent):void {
			updateChange();
		}
		protected function updateChange():void {
			dispatchEvent(new Event(Event.CHANGE));
		}
	}
}